<template>
  <div>
    <!--
      必填:
      action 上传地址, 因为用腾讯云, 所以用 # 代替
      file-list 用来管理图片

      list-type 控制样式

      on-preview 绑定后会显示放大镜, 点击后的弹窗回调需要另外写
     -->
    <el-upload
      :class="{ disable: fileList.lenth > 0 }"
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :on-preview="preview"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <el-progress
      v-if="showProgress"
      :text-inside="true"
      :stroke-width="26"
      :percentage="percentage"
      style="width: 146px"
    />

    <el-dialog title="预览" :visible="showDialog" @close="showDialog = false">
      <el-row type="flex" justify="center">
        <img :src="imgUrl" alt="" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5";

const cos = new COS({
  SecretId: "AKIDnPlriIbdOs51g5D4f06vUmpb6KHxMVNz",
  SecretKey: "MSHq9BwShfMmwpRntjIacNr41h6E5fy0",
});
export default {
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: "",
      showProgress: false,
      percentage: 0,
    };
  },
  methods: {
    preview(file) {
      // 每当点击,都可以获取到当前点击的图片对象
      // console.log(file);
      this.imgUrl = file.url;
      this.showDialog = true;
    },

    onRemove(file, fileList) {
      this.fileList = fileList;
    },
    onChange(file, fileList) {
      this.fileList = fileList;
    },
    upload(params) {
      // console.log(params);
      // console.log(params.file);
      this.showProgress = true;
      cos.putObject(
        {
          Bucket: "hr66-1304560168" /* 储存桶名称必须 */,
          Region: "ap-nanjing" /* 存储桶所在地域，必须字段 */,
          Key: params.file.name /* 上传的文件名称 */,
          StorageClass: "STANDARD" /* 固定储存类型不用更改 */,
          Body: params.file, // 上传文件对象
          onProgress: (progressData) => {
            /* 上传进度发生变化的回调 */
            // console.log("上传进度发生变化的回调", JSON.stringify(progressData));
            this.percentage = progressData.percent * 100;
          },
        },
        (err, data) => {
          if (!err) {
            /* 上传结束的回调 */
            // console.log("上传结束的回调", err || data);

            this.fileList[0].url = `http://${data.Location}`;
            this.fileList[0].status = "success";
            setTimeout(() => {
              this.showProgress = false;
            }, 1000);
          }
        }
      );
    },
    beforeUpload(file) {
      const maxSize = 2 * 1024 * 1024;
      if (file.size > maxSize) {
        this.$message.warning("仅支持2M以内的上传");
        return false;
      }
      const whiteList = ["image/jpeg", "image/png"];
      if (!whiteList.includes(file.type)) {
        this.$message.warning("当前只支持png和jpeg格式的图片");
        return false;
      }
    },
  },
};
</script>

<style lang="sass" scoped>
.disable
  ::v-deep .el-upload--picture-card
    display: none
</style>